Skip to content

regression: moment compatibility for admin date format settings#40304

Merged
dionisio-bot[bot] merged 6 commits intorelease-8.4.0from
fix/moment-bracket-literal-date-format
Apr 28, 2026
Merged

regression: moment compatibility for admin date format settings#40304
dionisio-bot[bot] merged 6 commits intorelease-8.4.0from
fix/moment-bracket-literal-date-format

Conversation

@dougfabris
Copy link
Copy Markdown
Member

@dougfabris dougfabris commented Apr 24, 2026

Proposed changes (including videos or screenshots)

Introduced here: #40076

  • After the 8.4 client migration from Moment.js to date-fns, admin-configured Moment format strings (Message_TimeAndDateFormat, Message_DateFormat, Message_TimeFormat) stopped working — [Today at] LT crashed the room view, YYYY-MM-DDTHH:mm:ss printed a millisecond timestamp instead of the T literal, and Z/ZZ/gg/gggg/kk/W/WW either threw or produced wrong output.
  • Replace the regex-based momentFormatToDateFns with a left-to-right tokenizer that handles [literal] escapes, longest-matches every Moment token from the Moment Display/Format docs, and quotes any unrecognized letter as a date-fns literal (so Moment's "unknown letter = literal" rule is preserved).
  • Map timezone offsets (Zxxx, ZZxx), week-year tokens (gg/gggg/GG/GGGG), era tokens (N..NNNNN), day-of-year tokens (DDD/DDDo/DDDD), and AM/PM casing (aaaa for lowercase). Pass useAdditionalWeekYearTokens and useAdditionalDayOfYearTokens to date-fns so those mappings actually format.
  • Wrap every format call in a safeFormat that falls back to LLL on any throw — a typo in the admin setting can no longer crash a room.

Test plan

  • On 8.3.2, set Message_TimeAndDateFormat to [Today at] LT, upgrade to this build, open a room — messages render and tooltips show Today at 8:30 PM.
  • Verify the QA-reported formats render without crashing on a fresh install: LT Z, YYYY-MM-DDTHH:mm:ss, YYYY-MM-DDTHH:mm:ssZ, Z ZZ, kk:mm, gggg-[W]WW-E, lll, h:mm a (lowercase).
  • Set a deliberately broken format (e.g. ]]not a format[[) and confirm the room still renders (falls back to LLL).

Issue(s)

Steps to test or reproduce

Further comments

CORE-2134

Summary by CodeRabbit

  • Tests
    • Added comprehensive tests for format-string conversion and formatting behavior, covering locale token mappings, literal text blocks and escaping, ISO "T" preservation, timezone and week/year tokens, extended fractional seconds, and end-to-end outputs.
  • Bug Fixes
    • Improved formatter to stream-translate Moment-style patterns to date-fns-compatible formats, honor bracket-escaped literals and quoting rules, correctly escape embedded quotes and literal "T", handle timezone/offset and week-year tokens, and use a centralized safe-formatting path with a non-throwing fallback.

@dionisio-bot
Copy link
Copy Markdown
Contributor

dionisio-bot Bot commented Apr 24, 2026

Looks like this PR is ready to merge! 🎉
If you have any trouble, please check the PR guidelines

@changeset-bot
Copy link
Copy Markdown

changeset-bot Bot commented Apr 24, 2026

⚠️ No Changeset found

Latest commit: 2abfd2f

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 24, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Reimplements Moment→date-fns format translation as a left-to-right tokenizer that preserves bracketed literals, performs longest-match token mapping, quotes stray letters, and adds a safeFormat wrapper that retries with a fallback; adds comprehensive Jest tests for mappings and literal handling.

Changes

Cohort / File(s) Summary
Core conversion & formatting
apps/meteor/client/lib/utils/dateFormat.ts
Replaced regex-based translator with a streaming left-to-right momentFormatToDateFns tokenizer that honors [...] literals (emit single-quoted date-fns literals, remove empty literals, double embedded single quotes), matches longest tokens, quotes unmapped letters, and added safeFormat to call date-fns with additional-token flags and retry using FALLBACK_FORMAT on error. Updated formatDate and formatTimeAgo to use safeFormat.
Tests
apps/meteor/client/lib/utils/dateFormat.spec.ts
Added Jest suite verifying wide token mappings (locale tokens, common tokens, day-of-year, ordinals, padded years, timezone tokens, fractional seconds, eras, ISO week/week-year tokens), bracketed-literal handling (including empty and embedded-quote cases and malformed brackets), ISO T quoting, and non-throwing fallback/format behavior.

Sequence Diagram(s)

sequenceDiagram
    participant Caller as formatDate / formatTimeAgo
    participant Translator as momentFormatToDateFns
    participant Safe as safeFormat
    participant DF as date-fns format
    participant Fallback as FALLBACK_FORMAT

    Caller->>Translator: provide Moment-style format string
    Translator-->>Caller: return date-fns-compatible format
    Caller->>Safe: pass date + converted format
    Safe->>DF: attempt format (with additional-token flags)
    alt success
        DF-->>Safe: formatted string
        Safe-->>Caller: return result
    else error
        Safe->>Fallback: retry with FALLBACK_FORMAT
        Fallback-->>Safe: formatted fallback string
        Safe-->>Caller: return fallback result
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Suggested labels

type: bug

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title directly addresses the core issue: a regression in moment compatibility for admin date format settings, which aligns with the PR's primary objective of fixing the handling of Moment's [literal] escape syntax.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

Warning

Review ran into problems

🔥 Problems

Errors were encountered while retrieving linked issues.

Errors (1)
  • CORE-2134: Request failed with status code 401

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@dougfabris dougfabris added this to the 8.4.0 milestone Apr 24, 2026
@codecov
Copy link
Copy Markdown

codecov Bot commented Apr 24, 2026

Codecov Report

❌ Patch coverage is 97.87234% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 69.99%. Comparing base (92dbb53) to head (2abfd2f).
⚠️ Report is 5 commits behind head on release-8.4.0.

Additional details and impacted files

Impacted file tree graph

@@                Coverage Diff                @@
##           release-8.4.0   #40304      +/-   ##
=================================================
+ Coverage          69.74%   69.99%   +0.24%     
=================================================
  Files               3298     3299       +1     
  Lines             119292   120261     +969     
  Branches           21469    21502      +33     
=================================================
+ Hits               83206    84175     +969     
- Misses             32785    32814      +29     
+ Partials            3301     3272      -29     
Flag Coverage Δ
e2e 59.71% <64.44%> (+0.04%) ⬆️
e2e-api 46.22% <ø> (-0.05%) ⬇️
unit 70.83% <97.34%> (+0.32%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@dougfabris dougfabris marked this pull request as ready for review April 25, 2026 20:36
@dougfabris dougfabris requested a review from a team as a code owner April 25, 2026 20:36
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
apps/meteor/client/lib/utils/dateFormat.ts (1)

43-61: Consider hoisting tokenMap, entries, and replaceTokens to module scope.

momentFormatToDateFns is invoked on every message/timestamp render. As written, each call rebuilds tokenMap, re-sorts entries, and constructs ~22 fresh RegExp objects inside replaceTokens. Since none of this depends on the input, moving them out of the function body would avoid the per-call allocation without changing behavior.

♻️ Proposed refactor
+const TOKEN_MAP: Record<string, string> = {
+	L: 'P',
+	LT: 'p',
+	LTS: 'pp',
+	LL: 'PPP',
+	LLL: 'PPP p',
+	LLLL: 'EEEE, PPP p',
+	YYYY: 'yyyy',
+	YY: 'yy',
+	Y: 'yyyy',
+	MMMM: 'MMMM',
+	MMM: 'MMM',
+	MM: 'MM',
+	M: 'M',
+	Do: 'do',
+	DD: 'dd',
+	D: 'd',
+	dddd: 'EEEE',
+	ddd: 'EEE',
+	HH: 'HH',
+	H: 'H',
+	hh: 'hh',
+	h: 'h',
+	mm: 'mm',
+	m: 'm',
+	ss: 'ss',
+	s: 's',
+	A: 'a',
+	a: 'a',
+};
+
+const TOKEN_ENTRIES: Array<[RegExp, string]> = Object.entries(TOKEN_MAP)
+	.sort(([a], [b]) => b.length - a.length)
+	.map(([mom, df]) => [new RegExp(mom.replace(/([.*+?^${}()|[\]\\])/g, '\\$1'), 'g'), df]);
+
+const replaceTokens = (input: string): string =>
+	TOKEN_ENTRIES.reduce((acc, [re, df]) => acc.replace(re, df), input);
+
 export const momentFormatToDateFns = (momentFormat: string): string => {
-	const tokenMap: Record<string, string> = { /* ... */ };
-	const entries = Object.entries(tokenMap).sort(([a], [b]) => b.length - a.length);
-
-	const replaceTokens = (input: string): string => {
-		let out = input;
-		for (const [mom, df] of entries) {
-			out = out.replace(new RegExp(mom.replace(/([.*+?^${}()|[\]\\])/g, '\\$1'), 'g'), df);
-		}
-		return out;
-	};
-
 	return momentFormat
 		.split(/(\[[^\]]*\])/g)
 		.map((part) => {
 			if (part.startsWith('[') && part.endsWith(']')) {
 				return `'${part.slice(1, -1).replace(/'/g, "''")}'`;
 			}
 			return replaceTokens(part);
 		})
 		.join('');
 };
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/meteor/client/lib/utils/dateFormat.ts` around lines 43 - 61, The code
repeatedly rebuilds tokenMap, entries, and replaceTokens on every call to
momentFormatToDateFns causing needless allocations; move tokenMap, the computed
entries (sorted Object.entries(tokenMap)), and the replaceTokens function to
module scope (outside momentFormatToDateFns) so they are created once. Ensure
replaceTokens still uses the hoisted entries and escapes regex metacharacters
the same way, and keep the existing per-call logic that splits momentFormat and
wraps bracketed literals; update any references inside momentFormatToDateFns to
use the hoisted symbols (tokenMap, entries, replaceTokens).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@apps/meteor/client/lib/utils/dateFormat.ts`:
- Around line 43-61: The code repeatedly rebuilds tokenMap, entries, and
replaceTokens on every call to momentFormatToDateFns causing needless
allocations; move tokenMap, the computed entries (sorted
Object.entries(tokenMap)), and the replaceTokens function to module scope
(outside momentFormatToDateFns) so they are created once. Ensure replaceTokens
still uses the hoisted entries and escapes regex metacharacters the same way,
and keep the existing per-call logic that splits momentFormat and wraps
bracketed literals; update any references inside momentFormatToDateFns to use
the hoisted symbols (tokenMap, entries, replaceTokens).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: f80463b1-56ca-4c74-ab43-e42431e920a4

📥 Commits

Reviewing files that changed from the base of the PR and between 957625f and b11f1c7.

📒 Files selected for processing (2)
  • apps/meteor/client/lib/utils/dateFormat.spec.ts
  • apps/meteor/client/lib/utils/dateFormat.ts
📜 Review details
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)

**/*.{ts,tsx,js}: Write concise, technical TypeScript/JavaScript with accurate typing in Playwright tests
Avoid code comments in the implementation

Files:

  • apps/meteor/client/lib/utils/dateFormat.spec.ts
  • apps/meteor/client/lib/utils/dateFormat.ts
**/*.spec.ts

📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)

**/*.spec.ts: Use descriptive test names that clearly communicate expected behavior in Playwright tests
Use .spec.ts extension for test files (e.g., login.spec.ts)

Files:

  • apps/meteor/client/lib/utils/dateFormat.spec.ts
🧠 Learnings (17)
📓 Common learnings
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 39397
File: packages/gazzodown/src/elements/Timestamp/DateTimeFormats.spec.tsx:20-23
Timestamp: 2026-03-06T18:09:17.867Z
Learning: In the RocketChat/Rocket.Chat gazzodown package (`packages/gazzodown`), tests are intended to run under the UTC timezone, but as of PR `#39397` this is NOT yet explicitly enforced in `jest.config.ts` or the `package.json` test scripts (which just run `jest` without `TZ=UTC`). To make timezone-sensitive snapshot tests reliable across all environments, `TZ=UTC` should be added to the test scripts in `package.json` or to `jest.config.ts` via `testEnvironmentOptions.timezone`. Without explicit UTC enforcement, snapshot tests involving date-fns formatted output or `toLocaleString()` will fail for contributors in non-UTC timezones.
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 37419
File: packages/i18n/src/locales/en.i18n.json:918-921
Timestamp: 2025-11-19T18:20:07.720Z
Learning: Repo: RocketChat/Rocket.Chat — i18n/formatting
Learning: This repository uses a custom message formatting parser in UI blocks/messages; do not assume standard Markdown rules. For keys like Call_ended_bold, Call_not_answered_bold, Call_failed_bold, and Call_transferred_bold in packages/i18n/src/locales/en.i18n.json, retain the existing single-asterisk emphasis unless maintainers request otherwise.
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 39397
File: packages/gazzodown/src/elements/Timestamp/RelativeTime.spec.tsx:63-70
Timestamp: 2026-03-06T18:02:20.381Z
Learning: In RocketChat/Rocket.Chat, tests in the `packages/gazzodown` package (and likely the broader test suite) are always expected to run in the UTC timezone. This makes `toLocaleString()` output deterministic, so snapshot tests that include locale/timezone-sensitive content (such as `title` attributes from `toLocaleString()`) are stable and do not need to be replaced with targeted assertions.
📚 Learning: 2026-03-06T18:09:17.867Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 39397
File: packages/gazzodown/src/elements/Timestamp/DateTimeFormats.spec.tsx:20-23
Timestamp: 2026-03-06T18:09:17.867Z
Learning: In the RocketChat/Rocket.Chat gazzodown package (`packages/gazzodown`), tests are intended to run under the UTC timezone, but as of PR `#39397` this is NOT yet explicitly enforced in `jest.config.ts` or the `package.json` test scripts (which just run `jest` without `TZ=UTC`). To make timezone-sensitive snapshot tests reliable across all environments, `TZ=UTC` should be added to the test scripts in `package.json` or to `jest.config.ts` via `testEnvironmentOptions.timezone`. Without explicit UTC enforcement, snapshot tests involving date-fns formatted output or `toLocaleString()` will fail for contributors in non-UTC timezones.

Applied to files:

  • apps/meteor/client/lib/utils/dateFormat.spec.ts
  • apps/meteor/client/lib/utils/dateFormat.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to apps/meteor/tests/e2e/**/*.spec.ts : Utilize Playwright fixtures (`test`, `page`, `expect`) for consistency in test files

Applied to files:

  • apps/meteor/client/lib/utils/dateFormat.spec.ts
📚 Learning: 2025-12-10T21:00:54.909Z
Learnt from: KevLehman
Repo: RocketChat/Rocket.Chat PR: 37091
File: ee/packages/abac/jest.config.ts:4-7
Timestamp: 2025-12-10T21:00:54.909Z
Learning: Rocket.Chat monorepo: Jest testMatch pattern '<rootDir>/src/**/*.spec.(ts|js|mjs)' is valid in this repo and used across multiple packages (e.g., packages/tools, ee/packages/omnichannel-services). Do not flag it as invalid in future reviews.

Applied to files:

  • apps/meteor/client/lib/utils/dateFormat.spec.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to apps/meteor/tests/e2e/**/*.spec.ts : All test files must be created in `apps/meteor/tests/e2e/` directory

Applied to files:

  • apps/meteor/client/lib/utils/dateFormat.spec.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to apps/meteor/tests/e2e/**/*.spec.ts : Group related tests in the same file

Applied to files:

  • apps/meteor/client/lib/utils/dateFormat.spec.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to apps/meteor/tests/e2e/**/*.spec.ts : Ensure tests run reliably in parallel without shared state conflicts

Applied to files:

  • apps/meteor/client/lib/utils/dateFormat.spec.ts
📚 Learning: 2026-03-06T18:02:20.381Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 39397
File: packages/gazzodown/src/elements/Timestamp/RelativeTime.spec.tsx:63-70
Timestamp: 2026-03-06T18:02:20.381Z
Learning: In RocketChat/Rocket.Chat, tests in the `packages/gazzodown` package (and likely the broader test suite) are always expected to run in the UTC timezone. This makes `toLocaleString()` output deterministic, so snapshot tests that include locale/timezone-sensitive content (such as `title` attributes from `toLocaleString()`) are stable and do not need to be replaced with targeted assertions.

Applied to files:

  • apps/meteor/client/lib/utils/dateFormat.spec.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to apps/meteor/tests/e2e/**/*.spec.ts : Use `expect` matchers for assertions (`toEqual`, `toContain`, `toBeTruthy`, `toHaveLength`, etc.) instead of `assert` statements in Playwright tests

Applied to files:

  • apps/meteor/client/lib/utils/dateFormat.spec.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to **/*.spec.ts : Use descriptive test names that clearly communicate expected behavior in Playwright tests

Applied to files:

  • apps/meteor/client/lib/utils/dateFormat.spec.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to apps/meteor/tests/e2e/**/*.spec.ts : Prefer web-first assertions (`toBeVisible`, `toHaveText`, etc.) in Playwright tests

Applied to files:

  • apps/meteor/client/lib/utils/dateFormat.spec.ts
📚 Learning: 2026-02-10T16:32:42.586Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 38528
File: apps/meteor/client/startup/roles.ts:14-14
Timestamp: 2026-02-10T16:32:42.586Z
Learning: In Rocket.Chat's Meteor client code, DDP streams use EJSON and Date fields arrive as Date objects; do not manually construct new Date() in stream handlers (for example, in sdk.stream()). Only REST API responses return plain JSON where dates are strings, so implement explicit conversion there if needed. Apply this guidance to all TypeScript files under apps/meteor/client to ensure consistent date handling in DDP streams and REST responses.

Applied to files:

  • apps/meteor/client/lib/utils/dateFormat.spec.ts
  • apps/meteor/client/lib/utils/dateFormat.ts
📚 Learning: 2026-02-24T19:22:48.358Z
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 38493
File: apps/meteor/tests/e2e/omnichannel/omnichannel-send-pdf-transcript.spec.ts:66-67
Timestamp: 2026-02-24T19:22:48.358Z
Learning: In Playwright end-to-end tests (e.g., under apps/meteor/tests/e2e/...), prefer locating elements by translated text (getByText) and ARIA roles (getByRole) over data-qa attributes. If translation values change, update the corresponding test locators accordingly. Never use data-qa locators. This guideline applies to all Playwright e2e test specs in the repository and helps keep tests robust to UI text changes and accessible semantics.

Applied to files:

  • apps/meteor/client/lib/utils/dateFormat.spec.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In the Rocket.Chat repository, do not reference Biome lint rules in code review feedback. Biome is not used even if biome.json exists; only reference Biome rules if there is explicit, project-wide usage documented. For TypeScript files, review lint implications without Biome guidance unless the project enables Biome rules.

Applied to files:

  • apps/meteor/client/lib/utils/dateFormat.spec.ts
  • apps/meteor/client/lib/utils/dateFormat.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In this repository (RocketChat/Rocket.Chat), Biome lint rules are not used even if a biome.json exists. When reviewing TypeScript files (e.g., packages/ui-voip/src/providers/useMediaSession.ts), ensure lint suggestions do not reference Biome-specific rules. Rely on general ESLint/TypeScript lint rules and project conventions instead.

Applied to files:

  • apps/meteor/client/lib/utils/dateFormat.spec.ts
  • apps/meteor/client/lib/utils/dateFormat.ts
📚 Learning: 2026-03-06T18:10:15.268Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 39397
File: packages/gazzodown/src/code/CodeBlock.spec.tsx:47-68
Timestamp: 2026-03-06T18:10:15.268Z
Learning: In tests (especially those using testing-library/dom/jsdom) for Rocket.Chat components, the HTML <code> element has an implicit ARIA role of 'code'. Therefore, screen.getByRole('code') or screen.findByRole('code') will locate <code> elements even without a role attribute. Do not flag findByRole('code') as invalid in reviews; prefer using the implicit role instead of adding role="code" unless necessary for accessibility.

Applied to files:

  • apps/meteor/client/lib/utils/dateFormat.spec.ts
📚 Learning: 2026-04-17T23:32:07.223Z
Learnt from: d-gubert
Repo: RocketChat/Rocket.Chat PR: 38357
File: apps/meteor/app/apps/server/converters/messages.ts:348-352
Timestamp: 2026-04-17T23:32:07.223Z
Learning: In `apps/meteor/app/apps/server/converters/messages.ts`, the `timestamp` handler inside `_convertAttachmentsToApp` uses a non-null assertion (`attachment.ts!`) intentionally. The `ts` property on `MessageAttachment` is optional only to accommodate MessageAttachment creation-time scenarios; by the time `_convertAttachmentsToApp` is called, the message has already been stored and the attachment is guaranteed to have a `ts` value. Do not flag this non-null assertion as unsafe during code review.

Applied to files:

  • apps/meteor/client/lib/utils/dateFormat.ts
🔇 Additional comments (2)
apps/meteor/client/lib/utils/dateFormat.ts (1)

53-61: Bracket-literal handling looks correct.

Verified the split + map pipeline against the relevant edge cases:

  • [Today at] LT'Today at' p
  • [it's]'it''s' (single-quote doubled) ✓
  • [] preserved as ''
  • [[] (Moment escape for literal [) is correctly captured by [^\]]* and emitted as '['
  • Token replacement is correctly scoped to non-literal segments, avoiding regressions where bracket contents like [on] were previously being token-replaced.
apps/meteor/client/lib/utils/dateFormat.spec.ts (1)

1-43: Test coverage looks solid and TZ-stable.

A few observations confirming this works across environments:

  • new Date('2026-04-24T20:30:45') parses as local time, and format outputs in local time, so the YYYY-MM-DD assertion at line 41 is stable regardless of the runner's timezone (the local date is always 2026-04-24).
  • The formatDate(sample, '[Today at] LT') test only matches the literal prefix, so locale/TZ-dependent time output won't make it flaky.
  • Coverage hits the regression scenarios well: literal segment, embedded ', and empty [].

Copy link
Copy Markdown
Member

@cardoso cardoso left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm a bit worried about the performance of momentFormatToDateFns. It's in some hot paths.

flowchart TD
    A[momentFormatToDateFns] --> B[formatDate]
    A --> C[formatTimeAgo]

    B --> D[useFormatDate]
    B --> E[useFormatTime]

    D --> F[MessageListProvider]
    F --> G[MessageListItem room timeline]
    D --> H[SidepanelItem and sidebar timestamps]
    D --> I[Threads MessageSearch BubbleDate]

    C --> J[useTimeAgo and useShortTimeAgo]
    C --> K[timeAgo legacy utility]

    J --> L[Relative timestamps in room and navigation UI]
Loading

Comment thread apps/meteor/client/lib/utils/dateFormat.ts Outdated
Comment thread apps/meteor/client/lib/utils/dateFormat.spec.ts
ggazzo
ggazzo previously approved these changes Apr 28, 2026
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
apps/meteor/client/lib/utils/dateFormat.ts (1)

6-20: Please drop the implementation comments in this helper.

This adds a large JSDoc block plus inline grouping comments in a TS implementation file where the repo guidance is to keep the code comment-free.

As per coding guidelines, "Avoid code comments in the implementation".

Also applies to: 24-70

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/meteor/client/lib/utils/dateFormat.ts` around lines 6 - 20, Remove the
large JSDoc block and inline grouping comments in this helper, leaving only the
code and any minimal single-line header if needed; specifically delete the
multiline comment that documents the Moment→date-fns translation above the
FALLBACK_FORMAT constant and any subsequent implementation comments within the
translate/formatter helper used by Message_DateFormat, Message_TimeFormat, and
Message_TimeAndDateFormat so the file conforms to the repo guideline of avoiding
implementation comments.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@apps/meteor/client/lib/utils/dateFormat.ts`:
- Around line 6-20: Remove the large JSDoc block and inline grouping comments in
this helper, leaving only the code and any minimal single-line header if needed;
specifically delete the multiline comment that documents the Moment→date-fns
translation above the FALLBACK_FORMAT constant and any subsequent implementation
comments within the translate/formatter helper used by Message_DateFormat,
Message_TimeFormat, and Message_TimeAndDateFormat so the file conforms to the
repo guideline of avoiding implementation comments.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c4004d05-276a-4a5c-9e4f-307871ace989

📥 Commits

Reviewing files that changed from the base of the PR and between b11f1c7 and e580b36.

📒 Files selected for processing (2)
  • apps/meteor/client/lib/utils/dateFormat.spec.ts
  • apps/meteor/client/lib/utils/dateFormat.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/meteor/client/lib/utils/dateFormat.spec.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: 📦 Build Packages
  • GitHub Check: CodeQL-Build
  • GitHub Check: CodeQL-Build
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)

**/*.{ts,tsx,js}: Write concise, technical TypeScript/JavaScript with accurate typing in Playwright tests
Avoid code comments in the implementation

Files:

  • apps/meteor/client/lib/utils/dateFormat.ts
🧠 Learnings (5)
📓 Common learnings
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 39397
File: packages/gazzodown/src/elements/Timestamp/DateTimeFormats.spec.tsx:20-23
Timestamp: 2026-03-06T18:09:17.867Z
Learning: In the RocketChat/Rocket.Chat gazzodown package (`packages/gazzodown`), tests are intended to run under the UTC timezone, but as of PR `#39397` this is NOT yet explicitly enforced in `jest.config.ts` or the `package.json` test scripts (which just run `jest` without `TZ=UTC`). To make timezone-sensitive snapshot tests reliable across all environments, `TZ=UTC` should be added to the test scripts in `package.json` or to `jest.config.ts` via `testEnvironmentOptions.timezone`. Without explicit UTC enforcement, snapshot tests involving date-fns formatted output or `toLocaleString()` will fail for contributors in non-UTC timezones.
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 37419
File: packages/i18n/src/locales/en.i18n.json:918-921
Timestamp: 2025-11-19T18:20:07.720Z
Learning: Repo: RocketChat/Rocket.Chat — i18n/formatting
Learning: This repository uses a custom message formatting parser in UI blocks/messages; do not assume standard Markdown rules. For keys like Call_ended_bold, Call_not_answered_bold, Call_failed_bold, and Call_transferred_bold in packages/i18n/src/locales/en.i18n.json, retain the existing single-asterisk emphasis unless maintainers request otherwise.
📚 Learning: 2026-04-17T23:32:07.223Z
Learnt from: d-gubert
Repo: RocketChat/Rocket.Chat PR: 38357
File: apps/meteor/app/apps/server/converters/messages.ts:348-352
Timestamp: 2026-04-17T23:32:07.223Z
Learning: In `apps/meteor/app/apps/server/converters/messages.ts`, the `timestamp` handler inside `_convertAttachmentsToApp` uses a non-null assertion (`attachment.ts!`) intentionally. The `ts` property on `MessageAttachment` is optional only to accommodate MessageAttachment creation-time scenarios; by the time `_convertAttachmentsToApp` is called, the message has already been stored and the attachment is guaranteed to have a `ts` value. Do not flag this non-null assertion as unsafe during code review.

Applied to files:

  • apps/meteor/client/lib/utils/dateFormat.ts
📚 Learning: 2026-02-10T16:32:42.586Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 38528
File: apps/meteor/client/startup/roles.ts:14-14
Timestamp: 2026-02-10T16:32:42.586Z
Learning: In Rocket.Chat's Meteor client code, DDP streams use EJSON and Date fields arrive as Date objects; do not manually construct new Date() in stream handlers (for example, in sdk.stream()). Only REST API responses return plain JSON where dates are strings, so implement explicit conversion there if needed. Apply this guidance to all TypeScript files under apps/meteor/client to ensure consistent date handling in DDP streams and REST responses.

Applied to files:

  • apps/meteor/client/lib/utils/dateFormat.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In the Rocket.Chat repository, do not reference Biome lint rules in code review feedback. Biome is not used even if biome.json exists; only reference Biome rules if there is explicit, project-wide usage documented. For TypeScript files, review lint implications without Biome guidance unless the project enables Biome rules.

Applied to files:

  • apps/meteor/client/lib/utils/dateFormat.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In this repository (RocketChat/Rocket.Chat), Biome lint rules are not used even if a biome.json exists. When reviewing TypeScript files (e.g., packages/ui-voip/src/providers/useMediaSession.ts), ensure lint suggestions do not reference Biome-specific rules. Rely on general ESLint/TypeScript lint rules and project conventions instead.

Applied to files:

  • apps/meteor/client/lib/utils/dateFormat.ts
🔇 Additional comments (2)
apps/meteor/client/lib/utils/dateFormat.ts (2)

22-75: Hoist the token table out of momentFormatToDateFns.

This helper sits on a hot rendering path, so rebuilding and resorting the same static mapping on every call is avoidable work.


80-120: Literal escaping path looks correct.

Buffering bracket literals and doubling embedded ' before emitting the date-fns literal is the right fix for formats like [Today at] LT, and it should prevent the unescaped-latin-character crash from resurfacing.

@dougfabris dougfabris changed the title regression: momentFormatToDateFns not handling literal date formats regression: moment.js compatibility for admin date format settings Apr 28, 2026
@dougfabris dougfabris changed the title regression: moment.js compatibility for admin date format settings regression: moment compatibility for admin date format settings Apr 28, 2026
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
apps/meteor/client/lib/utils/dateFormat.ts (1)

8-134: Please move the implementation commentary out of the module.

This change adds a lot of inline explanatory comments and a long doc block directly in the implementation. That makes the hot path harder to scan, and this repo’s JS/TS guideline asks us to avoid code comments in implementation files. As per coding guidelines: **/*.{ts,tsx,js}: Avoid code comments in the implementation.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/meteor/client/lib/utils/dateFormat.ts` around lines 8 - 134, The large
explanatory docblock and inline comments should be removed from the
implementation file and placed into a separate documentation file (e.g.,
docs/date-format-migration.md) or a top-level README; keep only minimal
docstring/comments near the translator function and constants for quick
reference. Specifically, extract the block describing differences between Moment
and date-fns and the detailed token-table commentary that surrounds
MOMENT_TO_DATE_FNS_TOKENS and LITERAL_LETTER, move that text to the new docs
file, and replace it in this module with a one-line summary comment referencing
the external doc and the translator function name (the token translator used by
Message_DateFormat / Message_TimeFormat / Message_TimeAndDateFormat) so the code
remains easy to scan.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/meteor/client/lib/utils/dateFormat.ts`:
- Around line 184-195: safeFormat currently always falls back to FALLBACK_FORMAT
("PPP p"), which can change granularity for callers like sameDayFormat and
lastDayFormat; update safeFormat (and its use of momentFormatToDateFns) to
detect the original momentFormat's granularity and choose a matching fallback
(e.g., FALLBACK_DATE for date-only patterns, FALLBACK_TIME for time-only
patterns, FALLBACK_DATETIME for combined patterns) instead of always using
FALLBACK_FORMAT. In practice, wrap the format call in the try/catch inside
safeFormat, and in the catch inspect the incoming momentFormat string for date
tokens (Y/y/M/D) vs time tokens (H/h/m/s/ a) to select the appropriate fallback
constant, then call format(d, chosenFallback, options); reference safeFormat,
momentFormatToDateFns, and FALLBACK_FORMAT/FALLBACK_DATE/FALLBACK_TIME to locate
where to implement this change.

---

Nitpick comments:
In `@apps/meteor/client/lib/utils/dateFormat.ts`:
- Around line 8-134: The large explanatory docblock and inline comments should
be removed from the implementation file and placed into a separate documentation
file (e.g., docs/date-format-migration.md) or a top-level README; keep only
minimal docstring/comments near the translator function and constants for quick
reference. Specifically, extract the block describing differences between Moment
and date-fns and the detailed token-table commentary that surrounds
MOMENT_TO_DATE_FNS_TOKENS and LITERAL_LETTER, move that text to the new docs
file, and replace it in this module with a one-line summary comment referencing
the external doc and the translator function name (the token translator used by
Message_DateFormat / Message_TimeFormat / Message_TimeAndDateFormat) so the code
remains easy to scan.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: ed924de2-5f04-4671-8161-6bbdc3d05b53

📥 Commits

Reviewing files that changed from the base of the PR and between 22faf04 and 2abfd2f.

📒 Files selected for processing (2)
  • apps/meteor/client/lib/utils/dateFormat.spec.ts
  • apps/meteor/client/lib/utils/dateFormat.ts
✅ Files skipped from review due to trivial changes (1)
  • apps/meteor/client/lib/utils/dateFormat.spec.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: CodeQL-Build
  • GitHub Check: CodeQL-Build
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)

**/*.{ts,tsx,js}: Write concise, technical TypeScript/JavaScript with accurate typing in Playwright tests
Avoid code comments in the implementation

Files:

  • apps/meteor/client/lib/utils/dateFormat.ts
🧠 Learnings (4)
📓 Common learnings
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 39397
File: packages/gazzodown/src/elements/Timestamp/DateTimeFormats.spec.tsx:20-23
Timestamp: 2026-03-06T18:09:17.867Z
Learning: In the RocketChat/Rocket.Chat gazzodown package (`packages/gazzodown`), tests are intended to run under the UTC timezone, but as of PR `#39397` this is NOT yet explicitly enforced in `jest.config.ts` or the `package.json` test scripts (which just run `jest` without `TZ=UTC`). To make timezone-sensitive snapshot tests reliable across all environments, `TZ=UTC` should be added to the test scripts in `package.json` or to `jest.config.ts` via `testEnvironmentOptions.timezone`. Without explicit UTC enforcement, snapshot tests involving date-fns formatted output or `toLocaleString()` will fail for contributors in non-UTC timezones.
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 37419
File: packages/i18n/src/locales/en.i18n.json:918-921
Timestamp: 2025-11-19T18:20:07.720Z
Learning: Repo: RocketChat/Rocket.Chat — i18n/formatting
Learning: This repository uses a custom message formatting parser in UI blocks/messages; do not assume standard Markdown rules. For keys like Call_ended_bold, Call_not_answered_bold, Call_failed_bold, and Call_transferred_bold in packages/i18n/src/locales/en.i18n.json, retain the existing single-asterisk emphasis unless maintainers request otherwise.
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 39397
File: packages/gazzodown/src/elements/Timestamp/RelativeTime.spec.tsx:63-70
Timestamp: 2026-03-06T18:02:20.381Z
Learning: In RocketChat/Rocket.Chat, tests in the `packages/gazzodown` package (and likely the broader test suite) are always expected to run in the UTC timezone. This makes `toLocaleString()` output deterministic, so snapshot tests that include locale/timezone-sensitive content (such as `title` attributes from `toLocaleString()`) are stable and do not need to be replaced with targeted assertions.
📚 Learning: 2026-02-10T16:32:42.586Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 38528
File: apps/meteor/client/startup/roles.ts:14-14
Timestamp: 2026-02-10T16:32:42.586Z
Learning: In Rocket.Chat's Meteor client code, DDP streams use EJSON and Date fields arrive as Date objects; do not manually construct new Date() in stream handlers (for example, in sdk.stream()). Only REST API responses return plain JSON where dates are strings, so implement explicit conversion there if needed. Apply this guidance to all TypeScript files under apps/meteor/client to ensure consistent date handling in DDP streams and REST responses.

Applied to files:

  • apps/meteor/client/lib/utils/dateFormat.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In the Rocket.Chat repository, do not reference Biome lint rules in code review feedback. Biome is not used even if biome.json exists; only reference Biome rules if there is explicit, project-wide usage documented. For TypeScript files, review lint implications without Biome guidance unless the project enables Biome rules.

Applied to files:

  • apps/meteor/client/lib/utils/dateFormat.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In this repository (RocketChat/Rocket.Chat), Biome lint rules are not used even if a biome.json exists. When reviewing TypeScript files (e.g., packages/ui-voip/src/providers/useMediaSession.ts), ensure lint suggestions do not reference Biome-specific rules. Rely on general ESLint/TypeScript lint rules and project conventions instead.

Applied to files:

  • apps/meteor/client/lib/utils/dateFormat.ts
🔇 Additional comments (1)
apps/meteor/client/lib/utils/dateFormat.ts (1)

135-182: Nice fix for Moment bracket literals.

The left-to-right tokenizer preserves [literal] blocks and correctly escapes embedded ' before handing the format to date-fns, which addresses the regression without reintroducing stray-token crashes.

Comment thread apps/meteor/client/lib/utils/dateFormat.ts
@dougfabris dougfabris requested a review from cardoso April 28, 2026 22:04
@rc-layne
Copy link
Copy Markdown

rc-layne Bot commented Apr 28, 2026

⚠️ Layne — 1 warning(s)

Found 1 issue(s): 1 medium.

@jessicaschelly jessicaschelly added the stat: QA assured Means it has been tested and approved by a company insider label Apr 28, 2026
@dionisio-bot dionisio-bot Bot added the stat: ready to merge PR tested and approved waiting for merge label Apr 28, 2026
@jessicaschelly jessicaschelly removed stat: ready to merge PR tested and approved waiting for merge stat: QA assured Means it has been tested and approved by a company insider labels Apr 28, 2026
@jessicaschelly jessicaschelly added the stat: QA assured Means it has been tested and approved by a company insider label Apr 28, 2026
@dionisio-bot dionisio-bot Bot added the stat: ready to merge PR tested and approved waiting for merge label Apr 28, 2026
@dionisio-bot dionisio-bot Bot merged commit f7e73ca into release-8.4.0 Apr 28, 2026
48 checks passed
@dionisio-bot dionisio-bot Bot deleted the fix/moment-bracket-literal-date-format branch April 28, 2026 23:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

stat: QA assured Means it has been tested and approved by a company insider stat: ready to merge PR tested and approved waiting for merge type: bug

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants